package com.yutel.amote.packet;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

import android.util.Log;

public class ClientHelper {
	final String TAG = "ClientHelper";
	private Socket client;
	private String ip;
	private int port;

	public ClientHelper(String ip,String port) {
		this.ip=ip;
		this.port=Integer.parseInt(port);
	}
	

	public boolean send(AbstractPacket packet) {
		ObjectOutputStream out = null;
		try {
			if(client==null || !client.isClosed()) {
				open();
			}
			out = new ObjectOutputStream(client.getOutputStream());
			out.writeObject(packet);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				if(out!=null){
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void finalize() {
		close();
	}
	private void open() throws Exception {
		try {
			Log.i(TAG,"open:---1-----");
			client = new Socket();
			InetAddress addr=Inet4Address.getByName(ip);
			client.connect(new InetSocketAddress(addr,port), 2000);
			Log.i(TAG,"open:---2-----");
		} catch (Exception e) {
			throw new Exception("connect server error:"+e);
		}
	}
	private void close() {
		try {
			client.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		client = null;
	}
}
